package com.moli.iov.protocol.codec;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Map;
import org.apache.kafka.common.serialization.Serializer;

/**
 * <p>
 *
 * </p>
 *
 * @author zql
 * @since 2019/10/18 15:42
 */
public class ObjectSerializer implements Serializer<Object> {

  @Override
  public void configure(Map<String, ?> configs, boolean isKey) {

  }

  @Override
  public byte[] serialize(String topic, Object data) {
    byte[] dataArray = null;
    try {
      //1、创建OutputStream对象
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      //2、创建OutputStream的包装对象ObjectOutputStream，PS：对象将写到OutputStream流中
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
      //3、将对象写到OutputStream流中
      objectOutputStream.writeObject(data);
      //4、将OutputStream流转换成字节数组
      dataArray = outputStream.toByteArray();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return dataArray;
  }

  @Override
  public void close() {

  }
}
